<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI对话沙盒 - 双AI实时对话</title>
    
    <!-- 国内CDN资源 -->
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.2/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --ai-a-color: #0d6efd;
            --ai-b-color: #6f42c1;
            --bg-color: #f8f9fa;
        }

        body {
            background-color: var(--bg-color);
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
        }

        .chat-container {
            height: 70vh;
            overflow-y: auto;
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
            background: white;
        }

        .message {
            margin: 0.5rem 0;
            padding: 0.75rem;
            border-radius: 0.5rem;
            max-width: 85%;
            word-wrap: break-word;
        }

        .message-ai-a {
            background-color: rgba(13, 110, 253, 0.1);
            border-left: 4px solid var(--ai-a-color);
            margin-left: 1rem;
            align-self: flex-start;
        }

        .message-ai-b {
            background-color: rgba(111, 66, 193, 0.1);
            border-right: 4px solid var(--ai-b-color);
            margin-right: 1rem;
            align-self: flex-end;
            text-align: right;
        }

        .message-header {
            font-weight: bold;
            margin-bottom: 0.25rem;
            font-size: 0.875rem;
        }

        .message-ai-a .message-header {
            color: var(--ai-a-color);
        }

        .message-ai-b .message-header {
            color: var(--ai-b-color);
        }

        .config-section {
            background: white;
            border-radius: 0.375rem;
            padding: 1rem;
            margin-bottom: 1rem;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        }

        .settings-drawer {
            position: fixed;
            top: 0;
            right: -400px;
            width: 400px;
            height: 100vh;
            background: white;
            box-shadow: -2px 0 5px rgba(0, 0, 0, 0.1);
            transition: right 0.3s ease;
            z-index: 1050;
            overflow-y: auto;
        }

        .settings-drawer.open {
            right: 0;
        }

        .settings-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1040;
            display: none;
        }

        .settings-overlay.show {
            display: block;
        }

        .typing-indicator {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .btn-group-custom {
            display: flex;
            gap: 0.5rem;
            flex-wrap: wrap;
        }

        .api-key-warning {
            background-color: #fff3cd;
            border: 1px solid #ffeaa7;
            color: #856404;
            padding: 0.75rem;
            border-radius: 0.375rem;
            margin-bottom: 1rem;
        }

        @media (max-width: 768px) {
            .settings-drawer {
                width: 100%;
                right: -100%;
            }
        }
    </style>
</head>
<body>
    <div class="container-fluid p-3">
        <h1 class="text-center mb-4">AI对话沙盒</h1>
        
        <!-- API密钥警告 -->
        <div id="apiKeyWarning" class="api-key-warning" style="display: none;">
            <i class="fas fa-exclamation-triangle"></i>
            <strong>提示：</strong>请在设置中配置您的OpenAI API密钥
        </div>

        <div class="row">
            <!-- 左侧配置区 -->
            <div class="col-lg-4 col-md-5">
                <div class="config-section">
                    <h5 class="mb-3">AI角色配置</h5>
                    
                    <!-- AI-A配置 -->
                    <div class="mb-3">
                        <label class="form-label">AI-A 名称</label>
                        <input type="text" class="form-control" id="aiAName" value="AI助手A" placeholder="输入AI-A的名称">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">AI-A 系统提示词</label>
                        <textarea class="form-control" id="aiAPrompt" rows="3" placeholder="设置AI-A的系统提示词">你是一个乐于助人的AI助手，请用简洁清晰的语言回答问题。</textarea>
                    </div>
                    
                    <hr>
                    
                    <!-- AI-B配置 -->
                    <div class="mb-3">
                        <label class="form-label">AI-B 名称</label>
                        <input type="text" class="form-control" id="aiBName" value="AI助手B" placeholder="输入AI-B的名称">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">AI-B 系统提示词</label>
                        <textarea class="form-control" id="aiBPrompt" rows="3" placeholder="设置AI-B的系统提示词">你是一个知识渊博的AI专家，请提供深入详细的分析和见解。</textarea>
                    </div>
                    
                    <button class="btn btn-primary w-100" onclick="updatePrompts()">
                        <i class="fas fa-sync"></i> 更新提示词
                    </button>
                </div>
            </div>
            
            <!-- 中央对话区 -->
            <div class="col-lg-8 col-md-7">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h6 class="mb-0">对话记录</h6>
                        <div class="btn-group-custom">
                            <button class="btn btn-sm btn-success" id="startBtn" onclick="startConversation()">
                                <i class="fas fa-play"></i> 开始对话
                            </button>
                            <button class="btn btn-sm btn-warning" id="pauseBtn" onclick="pauseConversation()" disabled>
                                <i class="fas fa-pause"></i> 暂停
                            </button>
                            <button class="btn btn-sm btn-danger" onclick="clearConversation()">
                                <i class="fas fa-trash"></i> 清空
                            </button>
                            <button class="btn btn-sm btn-info" onclick="exportConversation()">
                                <i class="fas fa-download"></i> 导出
                            </button>
                            <button class="btn btn-sm btn-secondary" onclick="toggleSettings()">
                                <i class="fas fa-cog"></i> 设置
                            </button>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <div class="chat-container" id="chatContainer">
                            <div class="d-flex flex-column p-3">
                                <div class="text-center text-muted p-5">
                                    <i class="fas fa-comments fa-3x mb-3"></i>
                                    <p>点击"开始对话"按钮启动AI对话</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 初始话题输入 -->
                <div class="mt-3">
                    <label class="form-label">初始话题</label>
                    <div class="input-group">
                        <input type="text" class="form-control" id="initialTopic" 
                               placeholder="输入对话初始话题（可选）" 
                               value="人工智能对未来社会的影响">
                        <button class="btn btn-outline-secondary" type="button" onclick="setInitialTopic()">
                            <i class="fas fa-arrow-right"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 设置抽屉 -->
    <div class="settings-overlay" onclick="toggleSettings()"></div>
    <div class="settings-drawer" id="settingsDrawer">
        <div class="p-4">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h5 class="mb-0">高级设置</h5>
                <button class="btn-close" onclick="toggleSettings()"></button>
            </div>
            
            <div class="mb-3">
                <label class="form-label">OpenAI API密钥</label>
                <input type="password" class="form-control" id="apiKey" 
                       placeholder="sk-..." value="">
                <div class="form-text">您的API密钥仅保存在浏览器本地存储中</div>
            </div>
            
            <div class="mb-3">
                <label class="form-label">API接口地址</label>
                <input type="text" class="form-control" id="apiUrl" 
                       value="https://api.openai.com/v1/chat/completions" 
                       placeholder="https://api.openai.com/v1/chat/completions">
            </div>
            
            <div class="mb-3">
                <label class="form-label">模型选择</label>
                <select class="form-select" id="modelSelect">
                    <option value="gpt-3.5-turbo">GPT-3.5 Turbo</option>
                    <option value="gpt-4">GPT-4</option>
                    <option value="gpt-4-turbo-preview">GPT-4 Turbo</option>
                </select>
            </div>
            
            <div class="mb-3">
                <label class="form-label">温度 (0-2)</label>
                <input type="range" class="form-range" id="temperature" 
                       min="0" max="2" step="0.1" value="0.7">
                <div class="text-center">
                    <span id="temperatureValue">0.7</span>
                </div>
            </div>
            
            <div class="mb-3">
                <label class="form-label">最大Token数</label>
                <input type="range" class="form-range" id="maxTokens" 
                       min="50" max="2000" step="50" value="500">
                <div class="text-center">
                    <span id="maxTokensValue">500</span>
                </div>
            </div>
            
            <div class="mb-3">
                <label class="form-label">对话间隔 (秒)</label>
                <input type="range" class="form-range" id="conversationDelay" 
                       min="1" max="10" step="0.5" value="2">
                <div class="text-center">
                    <span id="delayValue">2</span> 秒
                </div>
            </div>
            
            <button class="btn btn-primary w-100" onclick="saveSettings()">
                <i class="fas fa-save"></i> 保存设置
            </button>
        </div>
    </div>

    <!-- JavaScript -->
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.2/js/bootstrap.bundle.min.js"></script>
    <script>
        // 全局变量
        let conversation = [];
        let isRunning = false;
        let currentTurn = 'A';
        let conversationInterval = null;
        let settings = {
            apiKey: '',
            apiUrl: 'https://api.openai.com/v1/chat/completions',
            model: 'gpt-3.5-turbo',
            temperature: 0.7,
            maxTokens: 500,
            delay: 2
        };

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadSettings();
            updateRangeValues();
            checkApiKey();
        });

        // 设置相关函数
        function toggleSettings() {
            const drawer = document.getElementById('settingsDrawer');
            const overlay = document.querySelector('.settings-overlay');
            
            drawer.classList.toggle('open');
            overlay.classList.toggle('show');
        }

        function updateRangeValues() {
            document.getElementById('temperatureValue').textContent = 
                document.getElementById('temperature').value;
            document.getElementById('maxTokensValue').textContent = 
                document.getElementById('maxTokens').value;
            document.getElementById('delayValue').textContent = 
                document.getElementById('conversationDelay').value;
        }

        function saveSettings() {
            settings = {
                apiKey: document.getElementById('apiKey').value,
                apiUrl: document.getElementById('apiUrl').value,
                model: document.getElementById('modelSelect').value,
                temperature: parseFloat(document.getElementById('temperature').value),
                maxTokens: parseInt(document.getElementById('maxTokens').value),
                delay: parseFloat(document.getElementById('conversationDelay').value)
            };
            
            localStorage.setItem('aiChatSettings', JSON.stringify(settings));
            toggleSettings();
            checkApiKey();
            
            // 显示保存成功提示
            const toast = document.createElement('div');
            toast.className = 'alert alert-success position-fixed';
            toast.style.cssText = 'top: 20px; right: 20px; z-index: 9999;';
            toast.innerHTML = '<i class="fas fa-check"></i> 设置已保存';
            document.body.appendChild(toast);
            
            setTimeout(() => toast.remove(), 2000);
        }

        function loadSettings() {
            const saved = localStorage.getItem('aiChatSettings');
            if (saved) {
                settings = { ...settings, ...JSON.parse(saved) };
                
                document.getElementById('apiKey').value = settings.apiKey || '';
                document.getElementById('apiUrl').value = settings.apiUrl;
                document.getElementById('modelSelect').value = settings.model;
                document.getElementById('temperature').value = settings.temperature;
                document.getElementById('maxTokens').value = settings.maxTokens;
                document.getElementById('conversationDelay').value = settings.delay;
            }
        }

        function checkApiKey() {
            const warning = document.getElementById('apiKeyWarning');
            warning.style.display = settings.apiKey ? 'none' : 'block';
        }

        // 对话控制函数
        function startConversation() {
            if (!settings.apiKey) {
                alert('请先配置OpenAI API密钥');
                toggleSettings();
                return;
            }
            
            isRunning = true;
            document.getElementById('startBtn').disabled = true;
            document.getElementById('pauseBtn').disabled = false;
            
            if (conversation.length === 0) {
                const initialTopic = document.getElementById('initialTopic').value;
                if (initialTopic.trim()) {
                    conversation.push({
                        role: 'user',
                        content: initialTopic
                    });
                    displayMessage('用户', initialTopic, 'user');
                }
            }
            
            conversationInterval = setInterval(() => {
                if (isRunning) {
                    generateNextMessage();
                }
            }, settings.delay * 1000);
        }

        function pauseConversation() {
            isRunning = false;
            clearInterval(conversationInterval);
            document.getElementById('startBtn').disabled = false;
            document.getElementById('pauseBtn').disabled = true;
        }

        function clearConversation() {
            pauseConversation();
            conversation = [];
            document.getElementById('chatContainer').innerHTML = `
                <div class="d-flex flex-column p-3">
                    <div class="text-center text-muted p-5">
                        <i class="fas fa-comments fa-3x mb-3"></i>
                        <p>点击"开始对话"按钮启动AI对话</p>
                    </div>
                </div>
            `;
        }

        function setInitialTopic() {
            const topic = document.getElementById('initialTopic').value;
            if (topic.trim()) {
                clearConversation();
                conversation.push({
                    role: 'user',
                    content: topic
                });
                displayMessage('用户', topic, 'user');
            }
        }

        // 消息生成函数
        async function generateNextMessage() {
            const aiName = currentTurn === 'A' ? 
                document.getElementById('aiAName').value : 
                document.getElementById('aiBName').value;
            
            const systemPrompt = currentTurn === 'A' ?
                document.getElementById('aiAPrompt').value :
                document.getElementById('aiBPrompt').value;
            
            // 显示正在输入
            const typingIndicator = document.createElement('div');
            typingIndicator.className = `message message-ai-${currentTurn.toLowerCase()}`;
            typingIndicator.innerHTML = `
                <div class="message-header">${aiName}</div>
                <div class="typing-indicator"></div>
            `;
            document.querySelector('#chatContainer .d-flex').appendChild(typingIndicator);
            
            // 滚动到底部
            document.getElementById('chatContainer').scrollTop = 
                document.getElementById('chatContainer').scrollHeight;
            
            try {
                const messages = [
                    { role: 'system', content: systemPrompt },
                    ...conversation
                ];
                
                const response = await fetch(settings.apiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${settings.apiKey}`
                    },
                    body: JSON.stringify({
                        model: settings.model,
                        messages: messages,
                        temperature: settings.temperature,
                        max_tokens: settings.maxTokens
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const data = await response.json();
                const content = data.choices[0].message.content;
                
                // 移除正在输入指示器
                typingIndicator.remove();
                
                // 添加到对话历史
                conversation.push({
                    role: 'assistant',
                    content: content
                });
                
                // 显示消息
                displayMessage(aiName, content, `ai-${currentTurn.toLowerCase()}`);
                
                // 切换下一个AI
                currentTurn = currentTurn === 'A' ? 'B' : 'A';
                
            } catch (error) {
                console.error('Error:', error);
                typingIndicator.remove();
                
                const errorMsg = document.createElement('div');
                errorMsg.className = 'alert alert-danger m-3';
                errorMsg.innerHTML = `
                    <i class="fas fa-exclamation-triangle"></i>
                    生成消息时出错: ${error.message}
                `;
                document.querySelector('#chatContainer .d-flex').appendChild(errorMsg);
                
                pauseConversation();
            }
        }

        function displayMessage(sender, content, type) {
            const container = document.querySelector('#chatContainer .d-flex');
            
            // 如果是第一条消息，清除初始提示
            if (container.querySelector('.text-center')) {
                container.innerHTML = '';
            }
            
            const messageDiv = document.createElement('div');
            messageDiv.className = `message message-${type}`;
            messageDiv.innerHTML = `
                <div class="message-header">${sender}</div>
                <div>${content.replace(/\n/g, '<br>')}</div>
            `;
            
            container.appendChild(messageDiv);
            
            // 滚动到底部
            document.getElementById('chatContainer').scrollTop = 
                document.getElementById('chatContainer').scrollHeight;
        }

        // 导出功能
        function exportConversation() {
            if (conversation.length === 0) {
                alert('没有对话记录可导出');
                return;
            }
            
            const aiAName = document.getElementById('aiAName').value;
            const aiBName = document.getElementById('aiBName').value;
            
            let markdown = `# AI对话记录\n\n`;
            markdown += `**时间**: ${new Date().toLocaleString('zh-CN')}\n\n`;
            markdown += `**AI-A名称**: ${aiAName}\n`;
            markdown += `**AI-B名称**: ${aiBName}\n\n`;
            markdown += `---\n\n`;
            
            let turn = 0;
            conversation.forEach((msg, index) => {
                if (msg.role === 'user') {
                    markdown += `### 用户\n${msg.content}\n\n`;
                } else {
                    const aiName = turn % 2 === 0 ? aiAName : aiBName;
                    markdown += `### ${aiName}\n${msg.content}\n\n`;
                    turn++;
                }
            });
            
            const blob = new Blob([markdown], { type: 'text/markdown' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `ai-conversation-${Date.now()}.md`;
            a.click();
            URL.revokeObjectURL(url);
        }

        // 更新提示词
        function updatePrompts() {
            const toast = document.createElement('div');
            toast.className = 'alert alert-success position-fixed';
            toast.style.cssText = 'top: 20px; right: 20px; z-index: 9999;';
            toast.innerHTML = '<i class="fas fa-check"></i> 提示词已更新';
            document.body.appendChild(toast);
            
            setTimeout(() => toast.remove(), 2000);
        }

        // 监听范围输入变化
        document.getElementById('temperature').addEventListener('input', updateRangeValues);
        document.getElementById('maxTokens').addEventListener('input', updateRangeValues);
        document.getElementById('conversationDelay').addEventListener('input', updateRangeValues);
    </script>
</body>
</html>